package com.ruoyi.web.wx.controller;


import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.wx.entity.*;
import com.ruoyi.web.wx.service.*;
import com.ruoyi.web.wx.utils.*;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Controller
@RequestMapping("wx")
public class wxApitwo {
    @Autowired
    private ITrashService trashService;
    @Autowired
    private ITrashRecordService trashRecordService;
    @Autowired
    private ITrashRecordDetailsService trashRecordDetailsService;
    @Autowired
    private IWxUserService wxUserService;
    @Autowired
    private ICommunityManagerService communityManagerService;
    @Autowired
    private IEnvirBonusTotalService envirBonusTotalService;
    @Autowired
    private ITrashSettingService trashSettingService;
    @Autowired
    private IDeliverySiteService deliverySiteService;
    @Autowired
    private ITrashAutonomousRecordService trashAutonomousRecordService;
    @Autowired
    private ITrashAutonomousRecordDetailsService detailsService;
    /**
     *  获取可回收垃圾列表
     * @param
     * @return
     */
    @GetMapping("/trashType")
    @ResponseBody
    public Map trashType(String type) {
        Map map= new HashMap();
        if (StringUtils.isNotEmpty(type)){
            List<TrashVO> trashList = trashService.getListByType(type);
            map.put("trashList",trashList);
        }
        return map;
    }
    /**
     *  用户下单
     * @param
     * @return
     */
    @PostMapping("/add-trashorder")
    @ResponseBody
    public Map addtrashorder(@RequestBody TrashRecordVO trashRecordVO) {
        Map map= new HashMap();
        if (trashRecordVO!=null){
            trashRecordVO.setId(CommonUtil.getUUID());
            trashRecordVO.setReservationNum(CommonUtil.generatorOrderNumber(""));
            trashRecordVO.setStatus("1");
            trashRecordVO.setCreateTime(new Date());
            trashRecordService.insertTrashRecord(trashRecordVO);
            List<TrashRecordDetails> trashList = trashRecordVO.getTrashList();
            if (trashList!=null&&trashList.size()>0){
                for (TrashRecordDetails t : trashList) {
                    t.setTrashSetingId(t.getId());
                    t.setType("0");
                    t.setId(CommonUtil.getUUID());
                    t.setTrashRecordId(trashRecordVO.getId());
                    trashRecordDetailsService.insertTrashRecordDetails(t);
                }
            }
            map.put("status",1);
        }else {
            map.put("status",0);
        }
        return map;
    }
    /**
     *  获取可回收垃圾列表
     * @param
     * @return
     */
    @GetMapping("/trashorderList")
    @ResponseBody
    public Map trashorderList(@RequestParam(value="pageSize",defaultValue="10")Integer pageSize,@RequestParam(value="pageNum",defaultValue="1")Integer pageNum,String status,HttpServletRequest request) {
        Map map= new HashMap();
        String token = request.getHeader("token");
        String isWxuser = JwtUtil.getIsWxuser(token);
        Integer from=(pageNum-1)*pageSize;
        if ("1".equals(isWxuser)){
            String openId = JwtUtil.getUserId(token);
            WxUser wxUser = wxUserService.selectWxUserByOpenId(openId);
            //微信用户 查询属于自己订单
            TrashRecordVO trashRecord= new TrashRecordVO();
            trashRecord.setWxUserId(wxUser.getId());
            trashRecord.setStatus(status);
            trashRecord.setPageSize(pageSize);
            trashRecord.setFrom(from);
            List<TrashRecordVO> s =trashRecordService.selectTrashRecordListPage(trashRecord);
            for (TrashRecordVO trashRecordVO : s) {
                TrashRecordDetails trashRecordDetails= new TrashRecordDetails();
                trashRecordDetails.setTrashRecordId(trashRecordVO.getId());
                List<TrashRecordDetails> trashRecordDetails1 = trashRecordDetailsService.selectTrashRecordDetailsList(trashRecordDetails);
                trashRecordVO.setTrashList(trashRecordDetails1);
            }
            map.put("orderList",s);
        }else {
            String cmId = JwtUtil.getUserId(token);
            CommunityManager communityManager = communityManagerService.selectCommunityManagerById(cmId);
            String villages = communityManager.getVillages();
            //小区id
            String[] split = villages.split(",");
            //查询属于这个管理员的待接单内容
            if ("1".equals(status)||"0".equals(status)){
                //管理员用户查询 查看属于自己管辖小区的订单，且没有订单状态为待接单的
                List<TrashRecordVO> s =trashRecordService.selectWaitOrder(split,from,pageSize,status);
                for (TrashRecordVO trashRecordVO : s) {
                    TrashRecordDetails trashRecordDetails= new TrashRecordDetails();
                    trashRecordDetails.setTrashRecordId(trashRecordVO.getId());
                    List<TrashRecordDetails> trashRecordDetails1 = trashRecordDetailsService.selectTrashRecordDetailsList(trashRecordDetails);
                    trashRecordVO.setTrashList(trashRecordDetails1);
                }
                map.put("orderList",s);
            }if ("2".equals(status)||"3".equals(status)){
                TrashRecordVO trashRecord= new TrashRecordVO();
                trashRecord.setPageSize(pageSize);
                trashRecord.setFrom(from);
                trashRecord.setStatus(status);
                trashRecord.setCmId(cmId);
                List<TrashRecordVO> s = trashRecordService.selectTrashRecordList1(trashRecord);
                for (TrashRecordVO trashRecordVO : s) {
                    TrashRecordDetails trashRecordDetails= new TrashRecordDetails();
                    trashRecordDetails.setTrashRecordId(trashRecordVO.getId());
                    List<TrashRecordDetails> trashRecordDetails1 = trashRecordDetailsService.selectTrashRecordDetailsList(trashRecordDetails);
                    trashRecordVO.setTrashList(trashRecordDetails1);
                }
                map.put("orderList",s);
            }if (StringUtils.isEmpty(status)){
                //查看所有属于自己管辖的订单
                TrashRecordVO trashRecord= new TrashRecordVO();
                trashRecord.setPageSize(pageSize);
                trashRecord.setFrom(from);
                trashRecord.setCmId(cmId);
             List<TrashRecordVO> trashRecordVOS= trashRecordService.selectAllCm(trashRecord);
                for (TrashRecordVO trashRecordVO : trashRecordVOS) {
                    TrashRecordDetails trashRecordDetails= new TrashRecordDetails();
                    trashRecordDetails.setTrashRecordId(trashRecordVO.getId());
                    List<TrashRecordDetails> trashRecordDetails1 = trashRecordDetailsService.selectTrashRecordDetailsList(trashRecordDetails);
                    trashRecordVO.setTrashList(trashRecordDetails1);
                }
                map.put("orderList",trashRecordVOS);
            }
        }
        map.put("pageSize",pageSize);
        map.put("pageNum",pageNum);
        return map;
    }
    /**
     *  取消订单
     * @param
     * @return
     */
    @GetMapping("/CancellationOrder")
    @ResponseBody
    public Map CancellationOrder(String id) {
        Map map= new HashMap();
        if (StringUtils.isNotEmpty(id)){
            TrashRecord trashRecord = trashRecordService.selectTrashRecordById(id);
            if (trashRecord!=null&&!"3".equals(trashRecord.getStatus())){
                trashRecord.setStatus("0");
                trashRecordService.updateTrashRecord(trashRecord);
                map.put("status",1);
            }else {
                map.put("status",0);
            }

        }else {
            map.put("status",0);
        }
        return map;
    }
    /**
     *  确认接单
     * @param
     * @return
     */
    @GetMapping("/ordertaking")
    @ResponseBody
    public Map ordertaking(String id,HttpServletRequest request) {
        String token = request.getHeader("token");
        String cmid = JwtUtil.getUserId(token);
        CommunityManager communityManager = communityManagerService.selectCommunityManagerById(cmid);
        Map map= new HashMap();
        if (StringUtils.isNotEmpty(id)){
            TrashRecord trashRecord = trashRecordService.selectTrashRecordById(id);
            if (trashRecord!=null&&"1".equals(trashRecord.getStatus())){
                trashRecord.setStatus("2");
                trashRecord.setCmId(cmid);
                trashRecord.setCmName(communityManager.getName());
                trashRecordService.updateTrashRecord(trashRecord);
                map.put("status",1);
            }else {
                map.put("status",0);
            }
        }else {
            map.put("status",0);
        }
        return map;
    }
    /**
     *  获取预约订单详情
     * @param
     * @return
     */
    @GetMapping("/getTrashorderInfo")
    @ResponseBody
    public TrashRecordVO getTrashorderInfo(String id) {
        Map map= new HashMap();
        if (StringUtils.isNotEmpty(id)){
            TrashRecord trashRecord = trashRecordService.selectTrashRecordById(id);
            if (trashRecord!=null){
                TrashRecordVO trashRecordVO = new TrashRecordVO();
                BeanUtils.copyProperties(trashRecord,trashRecordVO);
                TrashRecordDetails trashRecordDetails= new TrashRecordDetails();
                trashRecordDetails.setTrashRecordId(trashRecordVO.getId());
                List<TrashRecordDetails> trashRecordDetails1 = trashRecordDetailsService.selectTrashRecordDetailsList(trashRecordDetails);
                trashRecordVO.setTrashList(trashRecordDetails1);
                return  trashRecordVO;
            }else {
                return null;
            }
        }else {
         return null;
        }
    }



    /**
     *  管理员确认回收
     * @param
     * @return
     */
    @PostMapping("/ConfirmTrashOrder")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public Map ConfirmTrashOrder(@RequestBody TrashRecordVO trashRecordVO,HttpServletRequest request) {
        TrashRecord trashRecord = trashRecordService.selectTrashRecordById(trashRecordVO.getId());
        Map map= new HashMap();
        if (trashRecordVO!=null&&"2".equals(trashRecord.getStatus())){
            trashRecord.setStatus("3");
            trashRecord.setSuccessTime(new Date());
            trashRecord.setConfirmTIme(trashRecordVO.getConfirmTIme());
            trashRecordService.updateTrashRecord(trashRecord);
            List<TrashRecordDetails> trashList = trashRecordVO.getTrashList();
           //总钱数
            double totalMoney=0;
            double totalIntegral=0;
            int a=0;
            if (trashList!=null&&trashList.size()>0){
                /*trashRecordService.deleteTrashRecordByRId(trashRecord.getId());*/
                for (TrashRecordDetails t : trashList) {
                    TrashSetting trashSetting = trashSettingService.selectTrashSettingById(t.getId());
                    Integer integral = trashSetting.getIntegral();
                    Double num = t.getNum();
                    double i =integral*num;
                    a = (int) Math.round(totalIntegral+=i);
                    t.setType("1");
                    totalMoney+=t.getMoney();
                    t.setTrashSetingId(t.getId());
                    t.setId(CommonUtil.getUUID());
                    t.setTrashRecordId(trashRecordVO.getId());
                    trashRecordDetailsService.insertTrashRecordDetails(t);
                }
            }
            //往 envir_bonus_total 插入数据\
            EnvirBonusTotal envirBonusTotal = new EnvirBonusTotal();
            envirBonusTotal.setId(CommonUtil.getUUID());
            envirBonusTotal.setWxUserId(trashRecord.getWxUserId());
            envirBonusTotal.setCreateTime(new Date());
            envirBonusTotal.setSource("1");
            envirBonusTotal.setType("1");
            envirBonusTotal.setMoney(totalMoney);
            envirBonusTotal.setIntegral(String.valueOf(a));
            envirBonusTotalService.insertEnvirBonusTotal(envirBonusTotal);
            //更新用户表钱数 和积分
            WxUser wxUser = wxUserService.selectWxUserById(trashRecord.getWxUserId());
            double totalMoney1 = wxUser.getTotalMoney();
            Integer historyTotalIntegral = wxUser.getHistoryTotalIntegral();
            if (historyTotalIntegral==null){
                historyTotalIntegral=0;
            }
            double historytotalMoney = wxUser.getHistorytotalMoney();
            wxUser.setTotalMoney(totalMoney1+totalMoney);
            wxUser.setHistoryTotalIntegral(historyTotalIntegral+a);
            wxUser.setHistorytotalMoney(historytotalMoney+totalMoney);
            wxUserService.updateWxUser(wxUser);
            map.put("status",1);
        }else {
            map.put("status",0);
        }
        return map;
    }

    /**
     *  获取用户列表
     * @param
     * @return
     */
    @GetMapping("/getUserList")
    @ResponseBody
    public Map getUserList(@RequestParam(value="pageSize",defaultValue="10")Integer pageSize,@RequestParam(value="pageNum",defaultValue="1")Integer pageNum,String realName) {
        Map<String, Object> map = new HashMap<>();
        Integer from=(pageNum-1)*pageSize;
       List<WxUser> users= wxUserService.selectWxUserListPage(pageSize,from,realName);
        for (WxUser wxUser : users) {
            wxUser.setAddress(wxUser.getCity()+wxUser.getDistrict()+wxUser.getStreet()+wxUser.getCommunity()+wxUser.getVillage()+wxUser.getBuildingNum()+"号楼"+wxUser.getUnitNum()+"单元"+wxUser.getRoom()+"室"+(StringUtils.isNotEmpty(wxUser.getDetailedAddress())?wxUser.getDetailedAddress():""));
        }
        map.put("pageSize",pageSize);
        map.put("pageNum",pageNum);
        map.put("users",users);
        return  map;
    }
    /**
     *  获取投放点列表
     * @param
     * @return
     */
    @GetMapping("/getdeliveSite")
    @ResponseBody
    public   List<DeliverySite> getdeliveSite(String name) {
        DeliverySite deliverySite = new DeliverySite();
        deliverySite.setName(name);
        deliverySite.setStatus("1");
        List<DeliverySite> deliverySites = deliverySiteService.selectDeliverySiteList(deliverySite);
        return  deliverySites;
    }

    /**
     *  用户下单
     * @param
     * @return
     */
    @PostMapping("/add-autotrashorder")
    @ResponseBody
    public Map addautotrashorder(@RequestBody TrashAutonomousRecordVO trashAutonomousRecord,HttpServletRequest request) {
        Map map= new HashMap();
        String token = request.getHeader("token");
        String cmid = JwtUtil.getUserId(token);
        CommunityManager communityManager = communityManagerService.selectCommunityManagerById(cmid);
        if (communityManager==null){
            map.put("status",0);
            return  map;
        }
        if (trashAutonomousRecord!=null){
            trashAutonomousRecord.setId(CommonUtil.getUUID());
            trashAutonomousRecord.setStatus("1");
            trashAutonomousRecord.setCmName(communityManager.getName());
            trashAutonomousRecord.setCmId(cmid);
            trashAutonomousRecord.setSuccessTime(new Date());
            trashAutonomousRecordService.insertTrashAutonomousRecord(trashAutonomousRecord);
            List<TrashAutonomousRecordDetails> trashList = trashAutonomousRecord.getTrashList();
            //总钱数
            double totalMoney=0;
            //总积分
            double totalIntegral=0;
            int a=0;
            if (trashList!=null&&trashList.size()>0){
                for (TrashAutonomousRecordDetails t : trashList) {
                    TrashSetting trashSetting = trashSettingService.selectTrashSettingById(t.getId());
                    Integer integral = trashSetting.getIntegral();
                    double num = t.getNum();
                    double i =integral*num;
                    a = (int) Math.round(totalIntegral+=i);
                    totalMoney+=t.getMoney();
                    t.setTrashSetingId(t.getId());
                    t.setId(CommonUtil.getUUID());
                    t.setTaRecordId(trashAutonomousRecord.getId());
                    detailsService.insertTrashAutonomousRecordDetails(t);
                }
                //往 envir_bonus_total 插入数据\
                EnvirBonusTotal envirBonusTotal = new EnvirBonusTotal();
                envirBonusTotal.setId(CommonUtil.getUUID());
                envirBonusTotal.setWxUserId(trashAutonomousRecord.getWxUserId());
                envirBonusTotal.setCreateTime(new Date());
                envirBonusTotal.setSource("2");
                envirBonusTotal.setType("0");
                envirBonusTotal.setMoney(totalMoney);
                envirBonusTotal.setIntegral(String.valueOf(a));
                envirBonusTotalService.insertEnvirBonusTotal(envirBonusTotal);
                //更新用户表钱数 和积分
                WxUser wxUser = wxUserService.selectWxUserById(trashAutonomousRecord.getWxUserId());
                double totalMoney1 = wxUser.getTotalMoney();
                Integer historyTotalIntegral = wxUser.getHistoryTotalIntegral();
                if (historyTotalIntegral==null){
                    historyTotalIntegral=0;
                }
                double historytotalMoney = wxUser.getHistorytotalMoney();
                wxUser.setTotalMoney(totalMoney1+totalMoney);
                wxUser.setHistoryTotalIntegral(historyTotalIntegral+a);
                wxUser.setHistorytotalMoney(historytotalMoney+totalMoney);
                wxUserService.updateWxUser(wxUser);
            }
            map.put("status",1);
        }else {
            map.put("status",0);
        }
        return map;
    }
    }
